﻿using Common.Library;
using InsertIntoDataBase;
using OnlineVideos.Data;
using OnlineVideos.Entities;
using PicasaMobileInterface;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.IO.IsolatedStorage;
using System.Linq;
using System.Linq.Expressions;
using System.Net;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Media;
using System.Xml.Linq;
using System.Xml.Serialization;

namespace Social_Celebrities
{
    public class RequestState
    {
        public HttpWebRequest customwebrequest
        {
            get;
            set;
        }
        public string customdata
        {
            get;
            set;
        }

    }
    public class BlogDetails
    {
        public string title
        {
            get;
            set;
        }
        public string url
        {
            get;
            set;
        }

    }
    public class UploadToBlog
    {
        public Page page = default(Page);
        public IAsyncResult asynchronousResults = default(IAsyncResult);
        public HttpWebRequest requests = default(HttpWebRequest);
        public bool Dependent = false;
        public bool agent = false;
        public string BlogName = string.Empty;
        public string PostTitle = string.Empty;
        public string PostType = string.Empty;
        public StringBuilder XMLData;
        public int PersonID = default(int);
        public string DefaultUrl = string.Empty;
        public AutoResetEvent auto = new AutoResetEvent(false);
        public List<ShareTables> TablesList = new List<ShareTables>();
        public string UserName = string.Empty;
        public string Password = string.Empty;

        public UploadToBlog(int personid, Page page1)
        {
            page = page1;
            PersonID = personid;
            BackgroundWorker bg = new BackgroundWorker();
            bg.DoWork += bg_DoWork;
            bg.RunWorkerAsync();
        }

        void bg_DoWork(object sender, DoWorkEventArgs e)
        {


            //OnlineVideoDataContext context = new OnlineVideoDataContext(Constants.DatabaseConnectionString);
            BlogCategoryTable bt = Task.Run(async () => await Constants.connection.Table<BlogCategoryTable>().Where(i => i.BlogType == "people").FirstOrDefaultAsync()).Result;
            BlogName = bt.BlogName;
            UserName = bt.BlogUserName;
            Password = bt.BlogPassword;

            BloggerInterface BI = new BloggerInterface(UserName, Password);
            uploadPost();
        }

        public void uploadPost()
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://www.blogger.com/feeds/default/blogs/");
            request.Method = "GET";
            request.Headers["Authorization"] = CONST.PIC_AUTH + CONST.AUTH_BToken;
            request.BeginGetResponse(new AsyncCallback(RequestBlogCompleted), request);
            auto.WaitOne();
        }

        private void RequestBlogCompleted(IAsyncResult result)
        {
            var request = (HttpWebRequest)result.AsyncState;
            var response = (HttpWebResponse)request.EndGetResponse(result);
            StreamReader responseReader = new StreamReader(response.GetResponseStream());
            string Title = BlogName;
            string AttributeValue = "http://schemas.google.com/g/2005#post";
            XElement MyXMLConfig = XElement.Load(responseReader);
            XNamespace atomNS = "http://www.w3.org/2005/Atom";
            IEnumerable<BlogDetails> blogdetail = from item in MyXMLConfig.Descendants(atomNS + "entry")
                                                  select new BlogDetails
                                                  {
                                                      title = item.Element(atomNS + "title").Value,
                                                      url = item.Elements(atomNS + "link").Where(a => a.Attribute("rel").Value == AttributeValue).Select(a => a.Attribute("href").Value).FirstOrDefault(),
                                                  };
            foreach (BlogDetails bb in blogdetail)
            {
                if (Title == bb.title)
                {
                    //DefaultUrl = bb.url;
                    //break;
                }
                else
                {
                    DefaultUrl = bb.url;
                    break;
                }
            }
            UploadItem();
        }

        public void UploadItem()
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(DefaultUrl);
            request.Method = "POST";
            request.ContentType = "application/atom+xml";
            request.Headers["Authorization"] = CONST.PIC_AUTH + CONST.AUTH_BToken;
            request.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallbackItem), request);
        }

        private void GetRequestStreamCallbackItem(IAsyncResult asynchronousResult)
        {
            //OnlineVideoDataContext context = new OnlineVideoDataContext(Constants.DatabaseConnectionString);
            HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
            XMLData = new StringBuilder("<NewDataSet>");
            CastProfile cp = new CastProfile();
            cp = Task.Run(async () => await Constants.connection.Table<CastProfile>().Where(i => i.PersonID == PersonID).FirstOrDefaultAsync()).Result;
            XDocument xmlDoc;
            XmlSerializer xmlSerializer = new XmlSerializer(typeof(CastProfile));
            XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
            ns.Add("", "");
            using (MemoryStream xmlStream = new MemoryStream())
            {
                xmlSerializer.Serialize(xmlStream, cp, ns);
                xmlStream.Position = 0;
                xmlDoc = XDocument.Load(xmlStream);
                XMLData.Append(xmlDoc.ToString());
            }

            List<Phone_SocialFeed> ps = new List<Phone_SocialFeed>();
            ps = Task.Run(async () => await Constants.connection.Table<Phone_SocialFeed>().Where(i => i.PersonId == PersonID).ToListAsync()).Result;
            foreach (Phone_SocialFeed sp in ps)
            {
                XDocument xmlDoc1;
                XmlSerializer xmlSerializer1 = new XmlSerializer(typeof(Phone_SocialFeed));
                XmlSerializerNamespaces ns1 = new XmlSerializerNamespaces();
                ns1.Add("", "");
                using (MemoryStream xmlStream = new MemoryStream())
                {
                    xmlSerializer1.Serialize(xmlStream, sp, ns1);
                    xmlStream.Position = 0;
                    xmlDoc1 = XDocument.Load(xmlStream);
                    XMLData.Append(xmlDoc1.ToString());
                }
            }
            XMLData.Append("</NewDataSet>");
            lock (this)
            {
                HttpWebRequest webrequest = (HttpWebRequest)WebRequest.Create(DefaultUrl);

                webrequest.Method = "POST";
                webrequest.ContentType = "application/atom+xml";
                webrequest.Headers["Authorization"] = CONST.PIC_AUTH + CONST.AUTH_BToken;
                RequestState state = new RequestState() { customwebrequest = webrequest, customdata = XMLData.ToString() };
                webrequest.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallbackItems), state);
                Monitor.Wait(this);
            }
        }

        private void GetRequestStreamCallbackItems(IAsyncResult asynchronousResult)
        {
            RequestState state = (RequestState)asynchronousResult.AsyncState;
            HttpWebRequest request = (HttpWebRequest)state.customwebrequest;
            asynchronousResults = asynchronousResult;
            requests = request;
            BlogData(asynchronousResults, requests, (string)state.customdata);

        }
        private void BlogData(IAsyncResult asynchronousResult, HttpWebRequest request, string datacustom = "")
        {

            if (string.IsNullOrEmpty(datacustom))
            {
                datacustom = XMLData.ToString();
            }
            Stream postStream = new MemoryStream();
            string contentformat = string.Empty;
            //OnlineVideoDataContext context = new OnlineVideoDataContext(Constants.DatabaseConnectionString);
            CastProfile cp = new CastProfile();
            cp = Task.Run(async () => await Constants.connection.Table<CastProfile>().Where(i => i.PersonID == PersonID).FirstOrDefaultAsync()).Result;

            string Rating = "4";
            contentformat = "<div style='float: left;'><table><tr><td><div style='float: top;'><img  src='" + cp.FlickrPersonImageUrl + "' width='200px' height='200px'/></div></td><td><p>" + cp.Name + "</p></td></tr></table>" + "<div style='display: none;' xmlns='http://www.w3.org/1999/xhtml'>" +
                       "<![CDATA[" + "??" + datacustom + "]]>" +
                         "</div></div>";
            string contents = "<entry xmlns='http://www.w3.org/2005/Atom'>" +
                      "<title type='text'>" + cp.Name + "</title>" +
                      "<category scheme='http://www.blogger.com/atom/ns#' term='" + cp.Name + "'/>" +
                      "<category scheme='http://www.blogger.com/atom/ns#' term='" + Rating + "'/>" +
                      "<category scheme='http://www.blogger.com/atom/ns#' term='hide'/>" +
                      "<content type='xhtml'>" +
                        contentformat +
                      "</content>" +
                      "</entry>";


            PostTitle = string.Empty;
            Stream ms = new MemoryStream(Encoding.UTF8.GetBytes(contents));
            postStream = request.EndGetRequestStream(asynchronousResult);
            byte[] buffer = new byte[ms.Length / 4];
            int bytesRead = -1;
            ms.Position = 0;
            while ((bytesRead = ms.Read(buffer, 0, buffer.Length)) > 0)
            {
                postStream.Write(buffer, 0, bytesRead);
            }
            ms.Flush();
            ms.Close();
            postStream.Flush();
            postStream.Close();
            request.BeginGetResponse(new AsyncCallback(RequestAlbumCompletedItem), request);

        }

        private void RequestAlbumCompletedItem(IAsyncResult result)
        {
            try
            {
                lock (this)
                {
                    var request = (HttpWebRequest)result.AsyncState;
                    var response = (HttpWebResponse)request.EndGetResponse(result);
                    StreamReader responseReader = new StreamReader(response.GetResponseStream());
                    string responseStr = responseReader.ReadToEnd();
                    page.Dispatcher.BeginInvoke(() =>
                    {
                        Border frameBorder = (Border)VisualTreeHelper.GetChild(Application.Current.RootVisual, 0);
                        TextBlock tb = frameBorder.FindName("Blog_Msg") as TextBlock;
                        tb.Text = "Successfully Shared To Blog";
                        Popup Adc = frameBorder.FindName("pop") as Popup;
                        Adc.IsOpen = true;
                    });

                    //OnlineVideoDataContext context = new OnlineVideoDataContext(Constants.DatabaseConnectionString);
                    if (agent == true)
                    {
                        ShareTable st = Task.Run(async () => await Constants.connection.Table<ShareTable>().Where(i => i.ShowID == PersonID).FirstOrDefaultAsync()).Result;
                        Constants.connection.DeleteAsync(st);
                    }
                    Monitor.Pulse(this);
                }
                auto.Set();
            }
            catch
            {
                //OnlineVideoDataContext context = new OnlineVideoDataContext(Constants.DatabaseConnectionString);
                CastProfile cp = new CastProfile();
                cp = Task.Run(async () => await Constants.connection.Table<CastProfile>().Where(i => i.PersonID == PersonID).FirstOrDefaultAsync()).Result;
                if (Task.Run(async () => await Constants.connection.Table<ShareTable>().FirstOrDefaultAsync()).Result != null)
                {
                    if (Task.Run(async () => await Constants.connection.Table<ShareTable>().Where(i => i.ShowID == PersonID).FirstOrDefaultAsync()).Result == null)
                    {
                        ShareTable st = new ShareTable();
                        st.ShowID = PersonID;
                        st.Description = "";
                        st.ImageUrl = cp.FlickrPersonImageUrl;
                        st.NextPostTime = System.DateTime.Now.AddDays(1);
                        st.BlogCategory = "";
                        Constants.connection.InsertAsync(st);

                    }
                    else
                    {
                        //OnlineVideoDataContext context1 = new OnlineVideoDataContext(Constants.DatabaseConnectionString);
                        ShareTable st = Task.Run(async () => await Constants.connection.Table<ShareTable>().Where(i => i.ShowID == PersonID).FirstOrDefaultAsync()).Result;
                        st.NextPostTime = st.NextPostTime.AddDays(1);
                        st.BlogCategory = "";
                        Constants.connection.UpdateAsync(st);
                    }
                }
                else
                {
                    ShareTable st = new ShareTable();
                    st.ShowID = PersonID;
                    st.Description = "";
                    st.ImageUrl = cp.FlickrPersonImageUrl;
                    st.NextPostTime = System.DateTime.Now.AddDays(1);
                    st.BlogCategory = "";
                    Constants.connection.InsertAsync(st);

                }
            }
            //Monitor.Pulse(this);
            auto.Set();
        }
    }
}
